#include "chatitembase.h"


ChatItemBase::ChatItemBase(ChatRole role, QWidget *parent) : QWidget(parent), m_role(role)
{
    m_pName_lb = new QLabel();
    m_pName_lb->setObjectName("chat_user_name");
    QFont font("Microsoft YaHei");
    font.setPointSize(9);
    m_pName_lb->setFont(font);
    m_pName_lb->setFixedHeight(20);

    m_pIcon_lb = new QLabel();
    m_pIcon_lb->setScaledContents(true);
    m_pIcon_lb->setFixedSize(42, 42);

    m_pBubble = new QWidget();

    QGridLayout* pGLayout = new QGridLayout();
    pGLayout->setVerticalSpacing(3);
    pGLayout->setHorizontalSpacing(3);
    pGLayout->setMargin(3);

    QSpacerItem* pSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    if (m_role == ChatRole::Self) {
        m_pName_lb->setContentsMargins(0, 0, 0, 0);
        m_pName_lb->setAlignment(Qt::AlignRight);
        pGLayout->addWidget(m_pName_lb, 0, 1, 1, 1);
        pGLayout->addWidget(m_pIcon_lb, 0, 2, 2, 1, Qt::AlignTop);
        pGLayout->addItem(pSpacer, 1, 0, 1, 1);
        pGLayout->addWidget(m_pBubble, 1, 1, 1, 1);
        pGLayout->setColumnStretch(0, 2);
        pGLayout->setColumnStretch(1, 3);
    } else {
        m_pName_lb->setContentsMargins(8, 0, 0, 0);
        m_pName_lb->setAlignment(Qt::AlignLeft);
        pGLayout->addWidget(m_pIcon_lb, 0, 0, 2, 1, Qt::AlignTop);
        pGLayout->addWidget(m_pName_lb,0, 1, 1, 1);
        pGLayout->addWidget(m_pBubble, 1, 1, 1, 1);
        pGLayout->addItem(pSpacer, 2, 2, 1, 1);
        pGLayout->setColumnStretch(1, 3);
        pGLayout->setColumnStretch(2, 2);
    }

    this->setLayout(pGLayout);

}

void ChatItemBase::setUserName(const QString &name)
{
    m_pName_lb->setText(name);
}

void ChatItemBase::setUserIcon(const QPixmap &icon)
{
    m_pIcon_lb->setPixmap(icon);
}

// 定制化实现气泡
void ChatItemBase::setWidget(QWidget *w)
{
    QGridLayout* pGLayout = (qobject_cast<QGridLayout*>)(this->layout());
    // 替换掉初始化时的widget
    pGLayout->replaceWidget(m_pBubble, w);
    delete m_pBubble;
    m_pBubble = w;
}
